package com.yenroc.ho.多线程;


import java.util.Date;

/**
 * ThreadLocal
 */
public class MyThread06 {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new MyThreadLocal()).start();
        }
    }

}


class MyThreadLocal implements Runnable {

    // 每个线程获取ThreadLocal变量时，总是使用Thread自身作为key
    // 因此，ThreadLocal相当于给每个线程都开辟了一个独立的存储空间，各个线程的ThreadLocal关联的实例互不干扰
    protected static ThreadLocal<String> name = new ThreadLocal<>();

    @Override
    public void run() {
        try {
            initName();
            printName();
            Thread.sleep(1000);
            printName2();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            clearName();// 线程结束要销毁线程变量
        }


    }

    private void initName(){
        name.set(Thread.currentThread().getName() + new Date().toString());
    }
    private void clearName(){
        name.remove();
    }


    private void printName(){
        System.out.println("printName="+ name.get());
    }

    private void printName2(){
        System.out.println("printName2="+ name.get());
    }
}
